const { SERVER_ERR } = require("../config/error.js");
const tagService = require("../service/tag.service.js");

class UserController {
  async create(ctx, next) {
    try {
      const { user ={}} = ctx;
      const { id: userId = 1 } = user;
      const { text = "" } = ctx.request.body;
      const res = await tagService.create({ text, userId });
      ctx.body = {
        code: 200,
        message: "创建成功",
        data: res,
      };
    } catch (error) {
      ctx.error = error;
      ctx.app.emit("error", SERVER_ERR, ctx);
    }
  }
  async delete(ctx, next) {
    try {
      const ids = ctx.request.body?.ids || [];
      const res = await tagService.delete(ids);
      ctx.body = {
        code: 200,
        message: "删除成功",
        data: res,
      };
    } catch (error) {
      ctx.error = error;
      ctx.app.emit("error", SERVER_ERR, ctx);
    }
  }
  async page(ctx, next) {
    try {
      const { user ={}} = ctx;
      const { id: userId = 1 } = user;
      const { pageNum, pageSize, text } = ctx.request.body;
      const res = await tagService.page({ pageNum, pageSize, text, userId });
      const res2 = await tagService.allNum(userId);
      ctx.body = {
        code: 200,
        message: "查询成功",
        data: res,
        total: res2,
      };
    } catch (error) {
      ctx.error = error;
      ctx.app.emit("error", SERVER_ERR, ctx);
    }
  }
  async update(ctx, next) {
    try {
      const { id, text = "" } = ctx.request.body;
      const res = await tagService.update({
        id,
        text,
      });
      ctx.body = {
        code: 200,
        message: "更新成功",
        data: res,
      };
    } catch (error) {
      ctx.error = error;
      ctx.app.emit("error", SERVER_ERR, ctx);
    }
  }
  async findName(ctx, next) {
    try {
      const { text, userId } = ctx.request.body;
      const res = await tagService.findName({ text, userId });
      ctx.body = {
        code: 200,
        message: "查询成功",
        data: res,
      };
    } catch (error) {
      ctx.error = error;
      ctx.app.emit("error", SERVER_ERR, ctx);
    }
  }
  async select(ctx, next) {
    try {
      const { user ={}} = ctx;
      const { id: userId = 1 } = user;
      const res = await tagService.select(userId);
      ctx.body = {
        code: 200,
        message: "查询成功",
        data: res,
      };
    } catch (error) {
      ctx.error = error;
      ctx.app.emit("error", SERVER_ERR, ctx);
    }
  }

    async detail(ctx, next) {
      try {
        const { id } = ctx.request.params;
        const res = await tagService.detail(id);
        
        ctx.body = {
          code: 200,
          message: "查询成功",
          data: res,
        };
      } catch (error) {
        ctx.error = error;
        ctx.app.emit("error", SERVER_ERR, ctx);
      }
    }
}

module.exports = new UserController();
